package org.neuedu.service;

import org.neuedu.bean.*;
import org.neuedu.dao.ArticleDao;
import org.neuedu.dao.ArticleDaoImpl;
import org.neuedu.dao.UserDao;
import org.neuedu.dao.UserDaoImpl;
import org.neuedu.utils.MD5Utils;

import java.util.List;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();

    @Override
    public int userReg(User user) {
        int count = userDao.serchUserByRegEmail(user.getEmail());
        if (count == 0) {
            // 密码加密
            user.setPassword(MD5Utils.MD5Encode(user.getPassword(), "utf8"));
            // 添加用户
            int i = userDao.saveUserInfo(user);
            if (i != 0) {
                // 根据邮箱把uid查询出来
                User user1 = userDao.serchUidByEmail(user);
                if (user1 != null) {
                    // 添加角色
                    userDao.saveRoleUserInfo(user1);
                }
            }
            return 1;
        }
        return 0;
    }

    @Override
    public User userLog(User user) {
        // 查询用户，若没有该应用直接返回
        user.setPassword(MD5Utils.MD5Encode(user.getPassword(), "utf8"));
        User user1 = userDao.serchUserByEmailAndPass(user);
        if (user1 != null) {
            // 查询用户角色信息
            List<Role> roles = userDao.serchRolesByUid(user1.getId());
            // 保存角色
            user1.setRoles(roles);
        }
        return user1;
    }

    @Override
    public User getUserById(Integer id) {
        // 查询文章详情+作者信息
        int userById = userDao.getUserById(id);
        User user = new User();
        user.setId(userById);
        return user;
    }

    @Override
    public int usersign(User user) {
        UserDao userDao = new UserDaoImpl();
        int userById = userDao.getUserById(user.getId());

        if (userById == 0) {
            userDao.updatetimeById(user.getId());
            userDao.updateKissById(user);
            return 1;
        }
        return 0;

    }

    @Override
    public int avatarPublish(User user) {
        int i= userDao.updateavatar(user);
        if(i==1){
        return 1;
     }     return 0;

    }

    @Override
    public int userInfoUpdate(User user) {
        int i = userDao.updateUserInfo(user);
        if (i != 0){
            return 1;
        }
        return 0;
    }

    @Override
    public int updatePasswordInfo(User user) {
        user.setPassword(MD5Utils.MD5Encode(user.getPassword(),"utf8"));
        int i = userDao.updatePasswordInfo(user);
        return i;
    }
}